package com.csr;

import java.text.DecimalFormat;
import java.util.ArrayList;

import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

public class ResellerResult extends Activity
{
	//TextView tvName,tvPhone,tvBalance,tvCategory;
	TextView tv_shopName;
	
	Button chkBoxFav;
	ResellerInfo agentInfo=AppData.agentInfo;
	Button btnBack,btnLogout;
	Handler handler=new Handler();
	MD5Generator md5Generator=new MD5Generator();
	HttpClient httpclient;
	HttpPost httppost = new HttpPost(AppData.hostURL+"/WebService/iTopUp/csrapp.php");
	ProgressDialog pd=null;
	private DataHelper dh;
	boolean isFav;
	@Override
	protected void onCreate(Bundle savedInstanceState) 
	{
		
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.agent_info_revised);
//		btnAddBalance=(Button)findViewById(R.id.btn_addBal);

	//	btnWeeklyStatement=(Button)findViewById(R.id.btn_weeklyStatement);
		ListView listView=(ListView)findViewById(R.id.list_agentInfo);
		btnBack=(Button)findViewById(R.id.btnPrevious);
	    btnLogout=(Button)findViewById(R.id.btnLogout);
		tv_shopName=(TextView)findViewById(R.id.tv_shopName);
		/*tvPhone=(TextView)findViewById(R.id.tv_phone);
		tvBalance=(TextView)findViewById(R.id.tv_bal);
		tvCategory=(TextView)findViewById(R.id.tv_CategoryType);*/
		chkBoxFav=(Button)findViewById(R.id.checkBoxAddToFav);
		String[] names = new String[]
			    {
			        "IMEI","Balance","Phone1",
			        "Phone 2","Alt Phone","Name",
			        "Account Name","ID Proof","ID Number",
			        "Address1","Address2","Area Name",
			        "ZipCode","State Name","Billing Template"
			        ,"Sales Executive","Email"
			    };
		
		String imei,balance,phn1,phn2,altphn,name,shopname,idproof,idnum,add1,add2,area,zipcode,state,bill,salesexecutive,email;
		ArrayList<String> s=new ArrayList<String>();
		imei=(agentInfo.getIMEI().trim().length()>0? agentInfo.getIMEI():"Not Available");
		balance=(agentInfo.getBalance().trim().length()>0? agentInfo.getBalance():"Not Available");
		phn1=(agentInfo.getPhone1().trim().length()>0?agentInfo.getPhone1():"Not Available");
		phn2=(agentInfo.getPhone2().trim().length()>0?agentInfo.getPhone2():"Not Available");
		altphn=(agentInfo.getAltPhone().trim().length()>0?agentInfo.getAltPhone():"Not Available");
		name=(agentInfo.getName().trim().length()>0?agentInfo.getName():"Not Available");
		shopname=(agentInfo.getAccountName().trim().length()>0?agentInfo.getAccountName():"Not Available");
		idproof=(agentInfo.getIDProofType().trim().length()>0?agentInfo.getIDProofType():"Not Available");
		idnum=(agentInfo.getIDNumber().trim().length()>0?agentInfo.getIDNumber():"Not Available");
		add1=(agentInfo.getAddress1().trim().length()>0?agentInfo.getAddress1():"Not Available");
		add2=(agentInfo.getAddress2().trim().length()>0?agentInfo.getAddress2():"Not Available");
		area=(agentInfo.getAreaName().trim().length()>0?agentInfo.getAreaName():"Not Available");
		zipcode=(agentInfo.getAreaZipCode().trim().length()>0?agentInfo.getAreaZipCode():"Not Available");
		state=(agentInfo.getStateName().trim().length()>0?agentInfo.getStateName():"Not Available");
		bill=(agentInfo.getBillingTemplate().trim().length()>0?agentInfo.getBillingTemplate():"Not Available");
		salesexecutive=(agentInfo.getSaleExecutive().trim().length()>0?agentInfo.getSaleExecutive():"Not Available");
		email=(agentInfo.getEmail().trim().length()>0?agentInfo.getEmail():"Not Available");
		
		String[] agentinfovalue=new String[]
		{
				imei,balance,phn1,phn2,altphn,name,shopname,idproof,idnum,add1,add2,area,zipcode,state,bill,salesexecutive,email
		};
		lv_info_adapter adapetr;
		adapetr=new lv_info_adapter(this,names,agentinfovalue);
//		MyListAdapter adpter=new MyListAdapter(ResellerResult.this, s); 
		listView.setAdapter(adapetr);
		tv_shopName.setText(agentInfo.getAccountName());
		
		/*	
		 * 
		 * tvCategory.append(":"+agentInfo.getDiscountMatrix());
			tvPhone.append(":"+agentInfo.getPhone1());
			tvBalance.append(":"+agentInfo.getBalance());
		*/
		
		Bundle bundle=getIntent().getExtras(); 
		
		if(!bundle.isEmpty())
		{
			if(bundle.getBoolean("istabactivity"))
			{
				LinearLayout ll=(LinearLayout)findViewById(R.id.headerlayout);
				ll.setVisibility(LinearLayout.GONE);
			}
		}
		if(isAgentInFav())
		{
			chkBoxFav.setBackgroundDrawable(getResources().getDrawable(R.drawable.favourite_marked)); 
			isFav=true;
		}
		
		
		
		
		chkBoxFav.setOnClickListener(new OnClickListener() 
		{
			
			
			public void onClick(View arg0) 
			{
				if(!isFav)
				{
		 			addToFav(agentInfo);
		 			isFav=true;
		 			chkBoxFav.setBackgroundDrawable(getResources().getDrawable(R.drawable.favourite_marked));
		 		}
		 		else
		 		{
		 			 
		 			removeFromFav(agentInfo);
		 			isFav=false;
		 			chkBoxFav.setBackgroundDrawable(getResources().getDrawable(R.drawable.favourite_unmarked));
		 		}
			}
			
			
			
			private void removeFromFav(ResellerInfo agentInfo) 
			{
				 try
				 {
					 dh=new DataHelper(ResellerResult.this);
					 dh.deleteProdctFromFav(agentInfo);
				}
				catch(Exception e)
				{
					e.printStackTrace();
				}
				finally
				{
					if(dh!=null)
					{
						dh.close();
					}
				} 
				 
			}

			private void addToFav(ResellerInfo agentInfo) 
			{
				try
				{
					dh=new DataHelper(ResellerResult.this);
					System.out.println("long:"+dh.insertToFav(agentInfo)); 
				}
				catch(Exception e)
				{
					e.printStackTrace();
				}
				finally
				{
					if(dh!=null)
					{
						dh.close();
					}
				}
			}
			
		}); 
		 
	  
        btnBack.setOnClickListener(new OnClickListener()
		{
			
			public void onClick(View arg0) 
			{
				// TODO Auto-generated method stub
				finish();
			}
			
		});
		
		btnLogout.setOnClickListener(new OnClickListener()
		{
			
			public void onClick(View v) 
			{
				new AlertDialog.Builder(ResellerResult.this)
		        .setTitle( "Exit Application" )
		        .setMessage( "Are you sure you want to Logout?" )
		        .setPositiveButton("YES", new android.content.DialogInterface.OnClickListener() 
		        {
		            public void onClick(DialogInterface arg0, int arg1) 
		            {
		            	setResult(2);
		            	finish();
		            }
  
		        })
		        .setNegativeButton("NO",  new android.content.DialogInterface.OnClickListener() {
		            public void onClick(DialogInterface arg0, int arg1)
		            {
		                //do stuff onclick of CANCEL
		            	arg0.dismiss();
		               
		            }

					public void onClick(View v) 
					{
						// TODO Auto-generated method stub
					}
		        }).show(); 
			}
		});
		
//		btnAddBalance.setOnClickListener(new OnClickListener()
//		{
//			
//			public void onClick(View arg0) 
//			{
//				 new AddBalanceDialog(ResellerResult.this).show(); 
//			}
//		});
		
//		btnInfo.setOnClickListener(new OnClickListener()
//		{
//			public void onClick(View v) 
//			{
//				// startActivity(new Intent(ResellerResult.this,ResellerInfoActivity.class));
//			}
//		});
		
		
//		btnWeeklyStatement.setOnClickListener(new OnClickListener()
//		{
//			
//			public void onClick(View v) 
//			{
//				// TODO Auto-generated method stub
//				Toast.makeText(ResellerResult.this,"Coming Soon..",Toast.LENGTH_SHORT).show();
//			}
//		});
	}
	private boolean isAgentInFav() 
	{
		try
		{
			dh=new DataHelper(ResellerResult.this);
			
			boolean status= dh.checkInFav(agentInfo);
			System.out.println("Returning"+status);
			return status;
			 
		}
		catch(Exception e)
		{
			e.printStackTrace();
			return false;
		}
		finally
		{
			if(dh!=null)
			{
				dh.close();
			}
		}
	}
	double roundTwoDecimals(double d) 
	{
        DecimalFormat twoDForm = new DecimalFormat("#.##");
        return Double.valueOf(twoDForm.format(d));
	}
	
	
	public static class ViewHolder
	 {
			public TextView tv_info;
			 
    }
	
	 class MyListAdapter extends ArrayAdapter<String> 
	 {
			
			private final Context context;
			/*private final String[] values;
			private final Integer[] icons;*/
			LayoutInflater vi ;
			 
			ArrayList<String> infoArray;
			 
			

			public MyListAdapter(Context context,ArrayList<String> infoArray)
			{
				super(context, R.layout.list_item,infoArray);
				 
				this.context = context;
				/*this.values = values;
				this.icons=icons;*/
				this.infoArray=infoArray;
				 
				vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
 
				
			}

			public View getView(final int position, View convertView, ViewGroup parent) 
			{
				View v = convertView;
				ViewHolder holder = null;
				
				if (v == null) 
				{
						holder=new ViewHolder();  
						v = vi.inflate(R.layout.list_item, null); 
						
						holder.tv_info=(TextView)v.findViewById(R.id.tv_info); 
						v.setTag(holder); 
					 
				}
				else
					holder=(ViewHolder)v.getTag(); 
					if(infoArray.get(position).trim().length()>0)
						holder.tv_info.setText(infoArray.get(position));
				 
				 	 
	 
				return v; 
			}//getView 

			 
		} 
	 /*private class AddBalanceDialog extends Dialog implements OnClickListener
	 {
		private Context context;
		private EditText etAmount,etTransactionPin;
		private Button btnOk,btnCancel,btnOkConfirmation,btnCancelConfirmation;
		private Double amount;
		private TextView tvConfirmationText,tvDialogHeader;
		
		public AddBalanceDialog(Context context) 
		{
			super(context);
			this.context=context;
			requestWindowFeature(Window.FEATURE_NO_TITLE);
			setContentView(R.layout.add_balance);
			etAmount=(EditText)findViewById(R.id.etAmount);
			etAmount.setInputType(InputType.TYPE_CLASS_NUMBER|InputType.TYPE_NUMBER_FLAG_DECIMAL);
			etTransactionPin=(EditText)findViewById(R.id.etTransactionPin);
			btnOk=(Button)findViewById(R.id.btn_ok);
			btnCancel=(Button)findViewById(R.id.btn_Cancel);
			btnOk.setOnClickListener(this);
			btnCancel.setOnClickListener(this);
		}
		
		public void onClick(View v) 
		{
			if (v == btnOk)
			{
				try
				{
					if(etAmount.getText().toString().trim().length()>0)
					{
						if(AppData.getUserInfo().getTransactionPassword().equals(md5Generator.MD5(etTransactionPin.getText().toString())))
						{
							dismiss();
							setContentView(R.layout.confirmation_layout); 
							tvConfirmationText=(TextView)findViewById(R.id.tvConfirmationText); 
							btnOkConfirmation=(Button)findViewById(R.id.btn_Ok_confirmation);
							btnCancelConfirmation=(Button)findViewById(R.id.btn_Continue_confirmation);
							tvConfirmationText.setText("Tuma "+etAmount.getText().toString() +" Tshs kwenda namba "+agentInfo.getPhone1()+".");
							btnOkConfirmation.setOnClickListener(this);
							btnCancelConfirmation.setOnClickListener(this);
							show(); 
							
						}
						else
						{
							Toast.makeText(context,"Invalid Transaction PIn",Toast.LENGTH_SHORT).show();
						}
						
					}
					else
					{
						Toast.makeText(ResellerResult.this,"Please Enter Amount.",Toast.LENGTH_SHORT).show(); 
					}
				}
				catch(Exception e)
				{
					e.printStackTrace();
				}
			}
			else if(v==btnCancel)
			{
				dismiss();
			}
			
			else if(v==btnOkConfirmation)
			{
				dismiss();		 
				amount =Double.parseDouble(etAmount.getText().toString())*100;
				new Thread(addBalance, "Add Balance").start();
				pd=ProgressDialog.show(ResellerResult.this,"please wait.",null);
				pd.setContentView(R.layout.progress);
				  
			}
			else if(v==btnCancelConfirmation)
			{
				dismiss();
			}	
			
		}*/
		
		/*private Runnable addBalance=new Runnable()
		{
			
			public void run()
			{
				try
				{
					httpclient = new DefaultHttpClient();
					String checksumString=
										AppData.getUserInfo().getLoginID()+"|"+
										agentInfo.getPhone1()+"|"+
										amount+"|"+
										AppData.getUserInfo().getpublickey();
					System.out.println("Check sum string===>"+checksumString);
					String finalChecksum = md5Generator.MD5(md5Generator.SHA1(checksumString));
					System.out.println("Final Checksum:"+finalChecksum);
					try 
					{     
					
						List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
						nameValuePairs.add(new BasicNameValuePair("function", "BalanceTransfer"));
					    nameValuePairs.add(new BasicNameValuePair("LoginId", AppData.getUserInfo().getLoginID()));
					    nameValuePairs.add(new BasicNameValuePair("Phone1", agentInfo.getPhone1()));
					    nameValuePairs.add(new BasicNameValuePair("Amount",Double.toString(amount)));
					   
					    nameValuePairs.add(new BasicNameValuePair("Checksum",finalChecksum)); 
					    
				 
					    httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
					    
					    ResponseHandler<String> responseHandler = new BasicResponseHandler();
					    
						String response = httpclient.execute(httppost,responseHandler);
						System.out.println("Response:"+response);
					    
						final JSONObject jsonObject=new JSONObject(response);
						
						  if(jsonObject.getString("ResponseCode").equals("000"))
			              {
							  
								handler.post(new Runnable()
								{ 
									public void run() 
									{
										try 
										{
											tvBalance.setText(""+roundTwoDecimals(Double.parseDouble(jsonObject.getString("Balance"))/100));
										} 
										catch (JSONException e) 
										{
											e.printStackTrace();
										}
										pd.dismiss();
										Toast.makeText(ResellerResult.this,"Balance Transfered Successfully",Toast.LENGTH_LONG).show();
										 
									}
								});
							  	 
			              }
						  else
						  {
							  handler.post(new Runnable()
			            	  {
								
								public void run() 
								{
									
									pd.dismiss();
									try 
									{
										Toast.makeText(ResellerResult.this,jsonObject.getString("ResponseDescription"),Toast.LENGTH_SHORT).show();
										
									}
									catch (JSONException e) 
									{
										e.printStackTrace();
									}
								}
							});
							  
						  }
					}
					catch (final JSONException e)
					{
						handler.post(new Runnable()
						{
							
							public void run() 
							{
								// TODO Auto-generated method stub
								pd.dismiss();
								Toast.makeText(ResellerResult.this,e.getMessage(),Toast.LENGTH_LONG).show(); 
							}
						});
					}
					catch(UnknownHostException e)
					{
						
						handler.post(new Runnable()
						{
							
							public void run() 
							{
								// TODO Auto-generated method stub
								pd.dismiss();
								Toast.makeText(ResellerResult.this,getString(R.string.conn_msg),Toast.LENGTH_LONG).show(); 
							}
						});
						 
					}
					catch (final ClientProtocolException e) 
					{
				        // TODO Auto-generated catch block
							handler.post(new Runnable()
							{
								
								public void run() 
								{
									// TODO Auto-generated method stub
									pd.dismiss();
									Toast.makeText(ResellerResult.this,getString(R.string.conn_msg),Toast.LENGTH_LONG).show(); 
								}
							});
							 
				    }
					
					catch (final IOException e) 
					{
							handler.post(new Runnable()
							{
								
								public void run() 
								{
									// TODO Auto-generated method stub
									pd.dismiss();
									Toast.makeText(ResellerResult.this, e.getMessage(),Toast.LENGTH_LONG).show();
								}
							}); 
				    }  
				}
				
				catch(Exception e)
				{
					e.printStackTrace();
				}
				
			}
		};
	 }//dialog
*/	
}
